<template>
  <van-popup v-model:show="_show" round position="bottom" :before-close="handleClose">
    <van-cascader
      :title="title"
      v-model="cascaderValue"
      :options="options"
      @close="handleClose"
      @finish="onFinish"
      @change="onChange"
    />
  </van-popup>
</template>
<script setup>
import http from '@/utils/http'

const emits = defineEmits(['update:modelValue', 'update:show', 'update:desc', 'change'])
const props = defineProps({
  title: { type: String, default: '请选择' },
  // options: Array,
  modelValue: String,
  show: { type: Boolean, default: false },
  desc: String,
  type: String,
})

const _show = ref(props.show)
const cascaderValue = ref('')

const options = ref([])

const getData = (pId = '0') => {
  return http('/district_institutions/subList', {
    params: {
      pId,
    },
  }).then(res => {
    if (!res) return

    return res.map(item => {
      const newItem = { id: item.id, text: item.text, value: item.value, value: item.value }

      if (item.children) {
        newItem.children = item.children.map(item => {
          return {
            id: item.id,
            text: item.text,
            value: item.id,
          }
        })
      }

      return newItem
    })
  })
}

getData().then(res => {
  options.value = res
})

watch(
  () => props.show,
  () => (_show.value = props.show)
)

watch(
  () => props.modelValue,
  () => (cascaderValue.value = props.modelValue)
)

const handleClose = () => emits('update:show', false)

const onChange = ({ value, selectedOptions, tabIndex }) => {
  if (props.type == 'native_place') return

  const current = selectedOptions[selectedOptions.length - 1]
  const id = current.id

  if (!id) return

  getData(id).then(res => {
    if (res?.length) current.children = res
  })
}

// 全部选项选择完毕后，会触发 finish 事件
const onFinish = ({ selectedOptions }) => {
  handleClose()
  emits('update:modelValue', cascaderValue.value)
  emits('update:desc', selectedOptions.map(option => option.text).join('/'))
  emits('change', selectedOptions)
}
</script>
<style lang="scss" scoped></style>
